package com.example.customview.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.example.customview.R
import com.example.customview.util.getBitmap
import com.sample.base.utils.dp

@SuppressLint("NewApi")
class CircleImageView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    companion object {
        private val IMAGE_WIDTH = 200f.dp
        private val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    }
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var layerBounds = RectF()

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        layerBounds = RectF(
            width / 2f - IMAGE_WIDTH / 2f,
            height / 2f - IMAGE_WIDTH / 2f,
            width / 2f + IMAGE_WIDTH / 2f,
            height / 2f + IMAGE_WIDTH / 2f
        )
    }

    override fun onDraw(canvas: Canvas) {
    // 开启离屏缓冲
        val count = canvas.saveLayer(layerBounds, null)
        canvas.drawOval(layerBounds, paint)
        paint.xfermode = xfermode
        canvas.drawBitmap(
            this.getBitmap(IMAGE_WIDTH, R.drawable.avatar),
            width / 2f - IMAGE_WIDTH / 2,
            height / 2f - IMAGE_WIDTH / 2,
            paint
        )
        paint.xfermode = null
        // 恢复离屏缓冲之前的状态
        canvas.restoreToCount(count)
    }
}